﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CARMSBusiness;
using CARMSData.CollectionClasses;
using CARMSData.EntityClasses;
using CARMSData.HelperClasses;
using CARMSData.StoredProcedureCallerClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using VitalShining.WebControls;

namespace CARMS.SysPage
{
    [Function("SysPage.PageGridConfig")]
    public partial class PageGridConfig :PageBase
    {
        private string CurrentActionID
        {
            get
            {
                return GetStringByParameter("ActionID");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                LoadDefault();
            }
        }

        private void LoadDefault()
        {
            if(!string.IsNullOrEmpty(CurrentActionID))
            {
                PageQueryAdapter1.PerformQuery();
            }
        }

        protected void PageQueryAdapter1_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            PredicateExpression Condition = new PredicateExpression(); 
            Condition.Add(ActionGridColumnFields.ActionId == CurrentActionID);
            e.Condition = Condition;
        }

        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var collection = new ActionGridColumnCollection();
            e.RecordCount = collection.GetDbCount((PredicateExpression)e.Condition);
        }

        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {
            SortExpression sort;
            switch (gridList.SortExpression)
            {

                //case "ActionID":
                //    sort = new SortExpression(ActionGridColumnFields.ActionId | (SortOperator)(int)gridList.SortDirection);
                //    break;
                //case "ActionName":
                //    sort = new SortExpression(ActionFields.ActionName | (SortOperator)(int)gridList.SortDirection);
                //    break;
                //case "ParentID":
                //    sort = new SortExpression(ActionFields.ParentId | (SortOperator)(int)gridList.SortDirection);
                //    break;

                //case "SortIndex":
                //    sort = new SortExpression(ActionFields.SortIndex | (SortOperator)(int)gridList.SortDirection);
                //    break;
                //case "CreateDate":
                //    sort = new SortExpression(ActionFields.CreateDate | (SortOperator)(int)gridList.SortDirection);
                //    break;
                default:
                    sort = new SortExpression(ActionGridColumnFields.ColumnName | SortOperator.Ascending);
                    break;
            }

            var collection = new ActionGridColumnCollection();
            collection.GetMulti((PredicateExpression)e.Condition, 0, sort, null, null, e.PageIndex + 1, e.PageSize);
            e.DataSource = collection;

        }

        protected void gridList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //var data = (ActionEntity)e.Row.DataItem;
                //var rptRoles = (Repeater)e.Row.FindControl("rptRoles");
                //if (rptRoles != null)
                //{
                //    var roles = SecurityBusiness.GetRoleListByActionID(data.ActionId);

                //    rptRoles.DataSource = roles;
                //    rptRoles.DataBind();
                //}
                //e.Row.Attributes["ActionId"] = data.ActionId.ToString();
            }
        }

        protected void gridList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "ModifyItem":
                    RediretResolveUrl(SiteUrls.SysPage.PageGridDetail + "?GridColumnID=" + e.CommandArgument);
                    break; 
            }
        }

        /// <summary>
        /// 从数据库中将 这个action 所对应的table 中的columns 全部取出，并添加到 ColumnToAction表中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRefreshColumnByDataBase_Click(object sender,EventArgs e)
        {
            var actionEntity = new ActionEntity(CurrentActionID);
            if(!actionEntity.IsNew)
            {
                var dataColumn = RetrievalProcedures.GetColumnsByTable(actionEntity.DbtableName);

           
                var gridcolumnCollection = new ActionGridColumnCollection();
                gridcolumnCollection.GetMulti(ActionGridColumnFields.ActionId == CurrentActionID);

                var strExistColumn = new List<string>();

                foreach (DataRow row in dataColumn.Rows)
                {
                    strExistColumn.Add(row["ColumnName"].ToString().ToUpper());
                    bool boolExist = false;
                    foreach (ActionGridColumnEntity gridColumnEntity in gridcolumnCollection)
                    {
                        if (row["ColumnName"].ToString().ToUpper() == gridColumnEntity.ColumnName)
                        {
                            boolExist = true;
                            //update 
                            var strColumnTypeName = row["ColumnTypeName"].ToString().ToUpper();
                            gridColumnEntity.ColumnDataType =strColumnTypeName;
                            if (strColumnTypeName == "NVARCHAR" || strColumnTypeName == "VARCHAR")
                            {
                                gridColumnEntity.ColumnLegnth = int.Parse(row["ColumnLength"].ToString())/2;
                            }
                            else
                            {
                                gridColumnEntity.ColumnLegnth = int.Parse(row["ColumnLength"].ToString());
                            }
                            gridColumnEntity.ColumnNullAble = row["ColumnNullAble"]=="1"?true:false;
                            gridColumnEntity.Save();
                        }
                    }
                    if(!boolExist)
                    {
                        //insert
                        var gridClmnEntity = new ActionGridColumnEntity();
                        gridClmnEntity.ActionId = CurrentActionID;
                        gridClmnEntity.ColumnName = row["ColumnName"].ToString().ToUpper();
                        var strColumnTypeName = row["ColumnTypeName"].ToString().ToUpper();
                        gridClmnEntity.ColumnDataType = strColumnTypeName;
                        if (strColumnTypeName == "NVARCHAR" || strColumnTypeName == "VARCHAR")
                        {
                            gridClmnEntity.ColumnLegnth = int.Parse(row["ColumnLength"].ToString()) / 2;
                        }
                        else
                        {
                            gridClmnEntity.ColumnLegnth = int.Parse(row["ColumnLength"].ToString());
                        } 
                        gridClmnEntity.ColumnNullAble = (row["ColumnNullAble"].ToString()=="1"?true:false);
                        gridClmnEntity.Save();
                    }
 
                }

                //删除 db 中 已经不存在的column
                var notExistList = from item in gridcolumnCollection
                                   where !strExistColumn.Contains(item.ColumnName)
                                   select item.GridColumnId;

                var condition = new FieldCompareRangePredicate(ActionGridColumnFields.GridColumnId, false, notExistList);
                var notExistCollection = new ActionGridColumnCollection();
                notExistCollection.DeleteMulti(condition);

                PageQueryAdapter1.PerformQuery();
            }
        }
    }
}
